package com.ybear.ybnetworkutil.network;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.ybear.ybnetworkutil.R;

/**
 * 网络状态改变监听服务
 */
@Deprecated(since = "高版本对网络监听不太友好，建议在发起请求时检查网络状态")
public class NetworkChangeService extends Service {
    private final NetworkChangeManage mNCM = NetworkChangeManage.get();
    private final NetworkConfig mConfig = NetworkConfig.get();
    private NetworkChangReceiver mReceiver = null;
    private int mNotificationId;

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            registerReceiver();
            if( mConfig.isEnableForegroundNotification() ) mNotificationId = startForeground();
            mNCM.setRunningService( true );
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if( mConfig.isEnableForegroundNotification() ) {
                if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ) {
                    stopForeground( mNotificationId );
                }else {
                    stopForeground( true );
                }
            }
            mNCM.setRunningService( false );
            unregisterReceiver();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) { return null; }

    /**
     * 注册广播
     */
    private void registerReceiver() {
        if( mReceiver != null ) return;
        mReceiver = new NetworkChangReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction( ConnectivityManager.CONNECTIVITY_ACTION );
        registerReceiver( mReceiver, filter );
    }

    /**
     * 解除注册广播
     */
    private void unregisterReceiver() {
        if( mReceiver == null ) { return; }
        unregisterReceiver( mReceiver );
        mReceiver = null;
    }

    /**
     创建一个通知
     */
    private int startForeground() {
        Context context = getApplicationContext();
        NotificationManager nm = (NotificationManager) getSystemService( NOTIFICATION_SERVICE );
        NetworkConfig config = NetworkConfig.get();
        int foregroundId = config.getForegroundId();
        String channelId = config.getNotificationChannelId();
        String channelName = config.getNotificationChannelName();
        int importance = config.getNotificationImportance();
        int smallIcon = config.getSmallIcon();
        Bitmap largeIcon = config.getLargeIcon() == -1 ?
                null :
                BitmapFactory.decodeResource( context.getResources(), config.getLargeIcon() );

        long when = System.currentTimeMillis();
        String title = config.getForegroundTitle();
        String content = config.getForegroundContent();

        Notification n;
        if( nm == null ) {
            n = new Notification();
            if( smallIcon != -1 ) n.icon = smallIcon;
            if( largeIcon != null ) n.largeIcon = largeIcon;
            n.when = when;
        }else {
            NotificationCompat.Builder b;
            if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
                //通知渠道
                @SuppressLint("WrongConstant")
                NotificationChannel nc = new NotificationChannel( channelId, channelName, importance );
                //小圆点
                nc.setShowBadge( false );
                //小气泡
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) nc.setAllowBubbles( false );
                //创建通知渠道
                nm.createNotificationChannel( nc );
                b = new NotificationCompat.Builder( context, channelId );
            }else {
                b = new NotificationCompat.Builder( context );
            }
            //后台标题
            if( !TextUtils.isEmpty( title ) ) b.setContentTitle( title );
            //后台内容
            if( !TextUtils.isEmpty( content ) ) b.setContentText( content );
            //小图标
            b.setSmallIcon( smallIcon != -1 ? smallIcon : R.drawable.ic_def_notify_small_icon );
            //大图标
            if( largeIcon != null ) {
                b.setLargeIcon( largeIcon );
            }
            //时间
            b.setWhen( when );
            n = b.build();
        }
        try {
            startForeground( foregroundId, n );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return foregroundId;
    }
}
